#import "ContentRequest.h"

@interface ContentRequest()
@property (nonatomic,assign)NSString *host;
@property (nonatomic,retain)AFHTTPSessionManager *manager;
@end

ContentRequest *default_content_request;
// content
@implementation ContentRequest
- (void)initReq:(RequestConfig*)config{
    _host = [config host];
    _manager = [config manager];
}
+ (id)defaultContentRequest{
    if (default_content_request == nil) {
        default_content_request = [[ContentRequest alloc]init];
        [default_content_request initReq:[RequestConfig defaultConfig]];
    }
    return default_content_request;
}
-(void)getPublicContents:(NSInteger)page eachPage:(NSInteger)eachPage success:(void (^)(NSArray<Content *> *))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/public?page=%ld&eachPage=%ld",_host,page,eachPage];
    [_manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            NSArray<NSDictionary*>*contents =responseObject[@"Data"];
            NSDictionary *content;
            NSMutableArray<Content*> *cs = [[NSMutableArray alloc]init];
            for (content in contents) {
                Content *c = [[Content alloc]initWith:content];
                [cs addObject:c];
            }
            success(cs);
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
-(void)getContentByID:(NSString *)contentID success:(void (^)(Content *))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/detail/%@",_host,contentID];
    [_manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            Content *c = [[Content alloc]initWith:responseObject[@"Data"]];
            success(c);
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
-(void)deleteContentByID:(NSString *)contentID success:(void (^)(void))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/%@",_host,contentID];
    [_manager DELETE:url parameters:nil headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            success();
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}


// text
-(void)getTextContents:(NSString *)userID success:(void (^)(NSMutableArray<Content*>*))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/texts/%@",_host,userID];
    [_manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            NSArray<NSDictionary*>*contents =responseObject[@"Data"];
            NSDictionary *content;
            NSMutableArray<Content*> *cs = [[NSMutableArray alloc]init];
            for (content in contents) {
                Content *c = [[Content alloc]initWith:content];
                [cs addObject:c];
            }
            success(cs);
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
-(void)postTextContent:(TextContent *)text success:(void (^)(void))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/text",_host];
    NSDictionary *dict;
    if (text.isPublic) {
        dict = @{@"title":text.title,@"detail":text.detail,@"tags":text.tags,@"isPublic":@YES};
    } else {
        dict = @{@"title":text.title,@"detail":text.detail,@"tags":text.tags,@"isPublic":@NO};
    }
    [_manager POST:url parameters:dict headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            success();
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
-(void)replaceTextContent:(NSString *)contentID text:(TextContent *)text success:(void (^)(void))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/all/%@",_host,contentID];
    NSDictionary *dict;
    if (text.isPublic) {
        dict = @{@"title":text.title,@"detail":text.detail,@"tags":text.tags,@"isPublic":@YES};
    } else {
        dict = @{@"title":text.title,@"detail":text.detail,@"tags":text.tags,@"isPublic":@NO};
    }
    [_manager PATCH:url parameters:dict headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            success();
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
// album
-(void)getAlbumContents:(NSString *)userID success:(nullable void (^)(NSMutableArray<Content *> *))success failure:(nullable void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/album/%@",_host,userID];
    [_manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            NSArray<NSDictionary*>*contents =responseObject[@"Data"];
            NSDictionary *content;
            NSMutableArray<Content*> *cs = [[NSMutableArray alloc]init];
            for (content in contents) {
                Content *c = [[Content alloc]initWith:content];
                [cs addObject:c];
            }
            success(cs);
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
-(void)postAlbumContent:(TextContent *)text withImages:(NSArray<UIImage *> *)images success:(void (^)(void))success failure:(void (^)(NSString *))failure{
    NSString *url = [NSString stringWithFormat:@"%@/content/text",_host];
    NSDictionary *dict;
    if (text.isPublic) {
        dict = @{@"title":text.title,@"detail":text.detail,@"tags":text.tags,@"isPublic":@YES};
    } else {
        dict = @{@"title":text.title,@"detail":text.detail,@"tags":text.tags,@"isPublic":@NO};
    }
    [_manager POST:url parameters:dict headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        int i=0;
        for (UIImage *image in images) {
            i=i+1;
            NSData *imageData = UIImagePNGRepresentation(image);
            NSData *thumbData = UIImageJPEGRepresentation(image, 0.4);
            [formData appendPartWithFormData:imageData name:[NSString stringWithFormat:@"file%d",i]];
            [formData appendPartWithFormData:thumbData name:[NSString stringWithFormat:@"thumb%d",i]];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"State"] isEqualToString:@"success"]){
            success();
        }else{
            failure(responseObject[@"State"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([NSString stringWithFormat:@"%@",error]);
    }];
}
-(void)getFileBy:(ContentFileReq *)req destination:(NSURL *)destination success:(void (^)(void))success failure:(void (^)(NSString *))failure{
    NSString *filePath = [[req filePath]stringByReplacingOccurrencesOfString:@"/" withString:@"|"];
    NSString *url = [NSString stringWithFormat:@"%@/content/file/%@/%@",_host,[req contentID],[filePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSLog(@"url:%@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDownloadTask *task = [_manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载速度%lld，总进度%lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
    } destination:^NSURL *(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [destination URLByAppendingPathComponent:@"img.jpg"];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"save to paht:%@",filePath);
    }];
    [task resume];
}
@end
